# -*- coding: utf-8 -*-
import json
import random
import time
import requests
import logging
from traceback import format_exc
from datetime import datetime
from requests import TooManyRedirects
from scrapy.utils.project import get_project_settings
from zc_core.middlewares.proxies.cached_pool import CachedProxyPool
from zc_core.model.items import Order
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_time, parse_number

from esgcc.simple.simple_dao import SimpleDao
from esgcc.simple.simple_session import SimpleSession

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s: %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename='order_list_home.log',
    filemode='a')
console = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(levelname)s: %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)

db_name_tpl = 'esgcc_{}'
# 登录会话管理
simple_session = SimpleSession()
# cookies = {'JSESSIONID': '5A4A65598E15B8EE363B0B3E0D0D9D1A', '__d_s_': '74DB46A51500E46F323D8DD2DA3ADE8A',
#            '__s_f_c_s_': '10AC30904622FD37BB2A5AE8319A49EB', '__t_c_k_': 'cd701743086843f686db3c44e5994509'}

# 构建校验器对象
settings = get_project_settings()
proxy_pool = CachedProxyPool(settings)
simple_dao = SimpleDao()


def send_req(page):
    order_list_url = 'http://b.esgcc.com.cn/showIndex/getLastestOrdersForHomePage.htm'
    headers = {
        'Host': 'b.esgcc.com.cn',
        'Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3766.400 QQBrowser/10.6.4163.400',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Referer': 'http://b.esgcc.com.cn/firstZoneIndex/index.htm'
    }
    data = json.dumps({
        "pgs": 10,
        "pgn": page,
        "orderId": "",
        "loginAccount": "",
        "transactionDesc": ""
    })
    try:
        # 登录获取cookie
        cookies = simple_session.get_cookies()
        rs = requests.post(
            url=order_list_url,
            cookies=cookies,
            headers=headers,
            data=data,
            timeout=90
        )
        return rs.text
    except TooManyRedirects as ex:
        logging.info('--> logout: %s' % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        simple_session.clean_cookies()


def parse_order_list_home(txt):
    order_list = list()
    rows = json.loads(txt)
    for row in rows:
        order_time = parse_time(row.get('ORDER_PAY_TIME_STR'))
        total_price = parse_number(row.get('ORDER_MONEY'))
        order = Order()
        order['_id'] = row.get('ORDER_ID')
        order['orderDept'] = row.get('TRANSACTION_DESC')
        order['supplierName'] = row.get('STORE_NAME', '')
        order['orderUser'] = row.get('LOGIN_ACCOUNT', '')
        order['totalPrice'] = total_price
        order['orderTime'] = order_time
        order['batchNo'] = time_to_batch_no(order_time)
        order['genTime'] = datetime.utcnow()
        order_list.append(order)
    return order_list


def work():
    try:
        logging.info('采集: %s' % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        txt = send_req(1)
        order_list = parse_order_list_home(txt)
        simple_dao.save_orders(order_list)
        logging.info('数量: %s' % len(order_list))
    except Exception as e:
        logging.info(format_exc())
        _ = e


if __name__ == '__main__':
    while True:
        work()
        time.sleep(random.randint(45, 75))
